#!/usr/bin/env python
#coding=utf-8
import yyWeb
import parse
import threading
import wx
import common.feedparser as feedparser
import random


class yyStop(Exception):
    pass

def getLeftUsers(user, info):
    '''从user中移除info信息中over为True的用户
    >>> user=[{'name':'tom', 'pwd':'123'},{'name':'jerry', 'pwd':'456'}]
    >>> info=[{'name':'tom', 'over':True}, {'name':'jerry', 'over':False}]
    >>> getLeftUsers(user,info)
    [{'pwd': '456', 'name': 'jerry'}]
    '''              
    for ainfo in info:
        if ainfo['over']:
            item = getItemFromOneKey(ainfo['name'], user)
            user.remove(item)
    return user

import types
def getIniFromObjType(obj): 
    '''
    >>> getIniFromObjType(u'uy')
    u''
    '''     
    if type(obj) == types.UnicodeType:
        return u''
    elif type(obj) == types.BooleanType:
        return False
    elif type(obj) == types.IntType:
        return 0
    elif type(obj) == types.ListType:
        return []
    else:
        return ''
                    
def getItemFromOneKey(name, info):
    '''从info里通过name找到相应的用户信息(浅拷贝——item修改后，原来的info也会跟着修改)
    >>> info = [{'name':'tom', 'age':16}, {'name':'jerry', 'age':19}]
    >>> item=getItemFromOneKey('tom',info)
    >>> item
    {'age': 16, 'name': 'tom'}
    >>> item['age']=18
    >>> info
    [{'age': 18, 'name': 'tom'}, {'age': 19, 'name': 'jerry'}]
    >>> ####找不到item时###
    >>> item=getItemFromOneKey('mark',info)
    >>> item
    {'age': 0, 'name': ''}
    >>> item['age']=18
    >>> info    
    [{'age': 18, 'name': 'tom'}, {'age': 19, 'name': 'jerry'}, {'age': 18, 'name': ''}]
    >>> ####开始为空时###
    >>> info = [{'name':'', 'age':0}]
    >>> item=getItemFromOneKey('mark',info)
    >>> item
    {'age': 0, 'name': ''}
    >>> item['age']=18
    >>> info    
    [{'age': 18, 'name': ''}]
    '''
    for i in info:
        if i['name'] == name:
            return i
    else:
        r = {}
        if info[0]['name']:
            for i in info[0].items():
                r[i[0]] = getIniFromObjType(i[1])
            info.append(r) 
            return r    
        else:
            return info[0]   

def getLeftFriends(fs, has_fs):
    '''取得没有踩过的好友
    >>> has_fs = ['1', '3']
    >>> fs = [{'name': 'a', 'id': '1'}, {'name': 'b', 'id': '2'}, {'name': 'c', 'id': '3'}]
    >>> getLeftFriends(fs, has_fs)
    [{'name': 'b', 'id': '2'}]
    '''
    for item in fs:
        if item['id'] in has_fs:
            fs.remove(item)
    return fs

class YYThread(threading.Thread):  
    def __init__(self, window, user, rss, tmessage, info, proxy):
        threading.Thread.__init__(self)
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        self.window = window
        
        self.user = user
        self.rss = rss
        self.tmessage = tmessage
        self.proxy = proxy
        self.info = info
        self.now_info = {}#当前登录者的信息
        self.twitter = []
    #user=[{'pwd': u'6', 'name': u'5'}, {'pwd': u'3', 'name': u'2'}, {'pwd': u'19840624', 'name': u'anquancyh@163.com'}, {'pwd': u'lixudong', 'name': u'lxdcyh@163.com'}]
    #rss=[{'url': u'http://rss.sina.com.cn/news/marquee/ddt.xml', 'name': u'\u65b0\u95fb\u8981\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/china/focus15.xml', 'name': u'\u56fd\u5185\u8981\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/world/focus15.xml', 'name': u'\u56fd\u9645\u8981\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/society/focus15.xml', 'name': u'\u793e\u4f1a\u65b0\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/china/politics15.xml', 'name': u'\u65f6\u653f\u8981\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/china/hktaiwan15.xml', 'name': u'\u6e2f\u6fb3\u53f0\u65b0\u95fb-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/society/law15.xml', 'name': u'\u793e\u4f1a\u4e0e\u6cd5-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/society/misc15.xml', 'name': u'\u793e\u4f1a\u4e07\u8c61-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/society/feeling15.xml', 'name': u'\u771f\u60c5\u65f6\u523b-\u65b0\u6d6a\u65b0\u95fb'}, {'url': u'http://rss.sina.com.cn/news/society/wonder15.xml', 'name': u'\u5947\u95fb\u8f76\u4e8b-\u65b0\u6d6a\u65b0\u95fb'}]
    #info=[{'init_renqi': 0, 'message_num': 0, 'name': '', 'has_daka': False, 'now_renqi': 0, 'has_blog': False, 'friends': [],over=False}]
     
    def stop(self):
        self.timeToQuit.set()

    def checkQuit(self):
        if self.timeToQuit.isSet():
            raise yyStop, u'停止'
    #login############################
    def uLogin(self, u):
        mainPage = self.login(u)
        if mainPage:
            if mainPage['error']:
                wx.CallAfter(self.window.messageCall, u'[%s]，请确认要登录的用户名和密码' % mainPage['error'])
                wx.CallAfter(self.window.btnStartCall, True)
                return False
            else:
                if mainPage.has_key('renqi'):
                    wx.CallAfter(self.window.messageCall, u'基本信息：%s' % mainPage)
                    self.now_info['name'] = u['name']
                    self.now_info['renqi'] = mainPage['renqi']
                    wx.CallAfter(self.window.infoCall, self.info)
                    return True
                else:
                    wx.CallAfter(self.window.messageCall, u'[%s]可能已经被挂起，请登录页面查看' % u['name'])
                    return False
        else:
            wx.CallAfter(self.window.messageCall, u'登录失败，请重新开始')
            wx.CallAfter(self.window.btnStartCall, True)
            return False
    
    def login(self, u):
        wx.CallAfter(self.window.messageCall, u'%s正在登录...' % u['name'])
        self.checkQuit()
        index = random.randint(0, len(self.proxy) - 1)
        self.web = yyWeb.YYWeb(proxy=self.proxy[index], logfile='', interval_time=2)
        f = self.web.login(u['name'], u['pwd'])
        mainPage = parse.parseMain(f)
        return mainPage
        
    #twitter#############################
    def step1(self):  
        self.getTwitter()  
        for u in self.user:
            self.uPostTwitter(u)
            
    def uPostTwitter(self, u):
        self.now_info = getItemFromOneKey(u['name'], self.info) #获取info
        if not self.now_info['has_twitter']:
            if self.uLogin(u):
                self.postTwitter()

    def getTwitter(self):  
        #从sina获取twitter内容     
        self.checkQuit()     
        import tsina
        
        tsinaWeb = tsina.TsinaWeb()
        f = tsinaWeb.getMain()
        ts = tsina.parseTsina(f)
        if ts:
            self.twitter = ts
            wx.CallAfter(self.window.messageCall, u'获取迷你博客模板列表成功')
        else:
            wx.CallAfter(self.window.messageCall, u'获取迷你博客模板列表失败')
                    
    def postTwitter(self):
        self.checkQuit()
        
        index = random.randint(0, len(self.twitter) - 1)
        content = self.twitter[index]
        
        f = self.web.postMiniBlog(content)
        twitterid = parse.parsePostTwitter(f)
        if twitterid:
            wx.CallAfter(self.window.messageCall, u'发表迷你博客成功')
            self.now_info['has_twitter'] = True
            wx.CallAfter(self.window.infoCall, self.info)            
        else:
            wx.CallAfter(self.window.messageCall, u'发表迷你博客失败')     
                   
    #cai################################  
    def step2(self):  
        for i in range(3):#0,1,2留言次数 
            wx.CallAfter(self.window.messageCall, u'===============第%s轮留言================' % (i + 1))
            for u in self.user:            
                self.uCai(u, i)
        
                     
    def uCai(self, u, num):
        self.now_info = getItemFromOneKey(u['name'], self.info) #获取info
                
        if self.now_info['message_num'] == num:
            if self.uLogin(u):
                self.commentTwitterAllFriends()
                self.now_info['friends'] = []
                self.now_info['message_num'] = num + 1
                if self.now_info['message_num'] == 3:
                    self.now_info['over'] = True
        else:
            wx.CallAfter(self.window.messageCall, u'[%s]本轮已踩过' % u['name'])
    
    def commentTwitterAllFriends(self):
        self.checkQuit()
        f = self.web.listFriends()
        f_list = parse.parseFriendsList(f)
        if f_list:
            f_no_main = getLeftFriends(f_list, ['491681'])#去掉主号#########todo提取导界面上
            fs = getLeftFriends(f_no_main, self.now_info['friends'])#获取没有踩过的好友
            wx.CallAfter(self.window.messageCall, u'获取好友列表成功，共[%s]好友，本轮还剩[%s]好友没有踩' % (len(f_no_main), len(fs)))
            self.commentTwitters(f, fs)
            if not self.now_info['has_daka']:
                self.daka()
        else:
            wx.CallAfter(self.window.messageCall, u'获取好友列表失败')
                    
    def commentTwitters(self, f, f_list):
        for f in f_list:
            friend_id = f['id']
            friend_name = f['name']
            self.checkQuit()
            f = self.web.listMiniBlogs(friend_id)
            miniBlog = parse.parseMiniBlogList(f)
            if miniBlog:
#                wx.CallAfter(self.window.messageCall, '获取［%s］迷你博客列表成功' % friend_name)
                userId = miniBlog['userId']
                id = miniBlog['id']
                index = random.randint(0, len(self.tmessage) - 1)
                content = self.tmessage[index]
#                content = u'不错' #################################留言应随机tooodoooooooooooooo
                self.checkQuit()
                f = self.web.saveMiniBlogComment(id, userId, content)
                r = parse.parseSaveMiniBlogError(f)
                if r:
                    if r['state'] == 0:
                        wx.CallAfter(self.window.messageCall, u'给［%s］留言出现错误：%s' % (friend_name, r['info']))
                    elif r['state'] == 1:
                        wx.CallAfter(self.window.messageCall, u'给［%s］留言成功，获得人气：%s' % (friend_name, r['info']))
                        self.now_info['friends'].append(friend_id)
                    elif r['state'] == 2:
                        wx.CallAfter(self.window.messageCall, u'给［%s］留言成功，但是没有获得人气' % friend_name)
                        self.now_info['friends'].append(friend_id)
                else:
                    wx.CallAfter(self.window.messageCall, u'给［%s］留言失败' % friend_name)
            else:
                wx.CallAfter(self.window.messageCall, u'今天［%s］没有发表新迷你博客' % friend_name)

    def daka(self):
        self.checkQuit()
        f = self.web.daka()
        r = parse.parseDaka(f)
        if r:
            if r['state'] == 0:
                wx.CallAfter(self.window.messageCall, u'打卡出现错误：%s' % r['info'])
            elif r['state'] == 1:
                wx.CallAfter(self.window.messageCall, u'打卡成功，获得人气：%s' % r['info'])
                self.now_info['has_daka'] = True
            elif r['state'] == 2:
                wx.CallAfter(self.window.messageCall, u'今天已经打过卡了') 
                self.now_info['has_daka'] = True           
        else:
            wx.CallAfter(self.window.messageCall, u'打卡失败')
            
    #main################################            
    def run(self): 
#        self.timeToQuit.wait(self.messageDelay)
        self.user = getLeftUsers(self.user, self.info)
        try:
            self.step1()
            self.step2()
            
            wx.CallAfter(self.window.messageCall, u'结束')
            wx.CallAfter(self.window.btnStartCall, True)            
        except yyStop, ex:
            wx.CallAfter(self.window.messageCall, str(ex))
            


    ######################################################

    ######################################################  
#def getRss(rss):        
#    d = feedparser.parse(rss['url'])    
    
#    def postBlog(self):
#        f = self.web.listMyBlog()
#        r = parse.parseMyBlogList(f)
#        categoryid = r['id']
#        wx.CallAfter(self.window.messageCall, 'categoryid:%s' % categoryid)
#        if categoryid:
#            title, content = getRss(self.rss)
#            
#            title = '今天天气不错'#################################从qq空间取
#            content = '周末了，出去玩会'#################################从qq空间取
#            f = self.web.postBlog(title, content, categoryid)
#            blogid = parse.parsePostBlog(f)
#            if blogid:
#                wx.CallAfter(self.window.messageCall, '发表博客成功')
#            else:
#                wx.CallAfter(self.window.messageCall, '发表博客失败')
#        else:
#            wx.CallAfter(self.window.messageCall, '博客列表获取失败')    
    
          
#    def commentAllFriends(self):
#        f = self.web.listFriends()
#        f_list = parse.parseFriendsList(f)
#        if f_list:
#            for f in f_list:
#                friend_id = f['id']
#                wx.CallAfter(self.window.messageCall, '获取%s博客列表' % friend_id)
#                f = self.web.listBlogs(friend_id)
#                newblog = parse.parseBlogList(f)
#                if newblog:
#                    blogid = newblog['blogid']
#                    id = newblog['id']
#                    title = newblog['title']
#                    comment = '不错'#################################留言应随机
#                    f = self.web.saveBlogComment(blogid, id, comment, title)
#                    r = parse.parseSaveBlogError(f)
#                    if r:
#                        if r['state'] == 0:
#                            wx.CallAfter(self.window.messageCall, '给%s留言出现错误：%s' % (id, r['info']))
#                        elif r['state'] == 1:
#                            wx.CallAfter(self.window.messageCall, '给%s留言成功，获得人气：%s' % (id, r['info']))
#                        elif r['state'] == 2:
#                            wx.CallAfter(self.window.messageCall, '给%s留言成功，但是没有获得人气' % id)
#                    else:
#                        wx.CallAfter(self.window.messageCall, '给%s留言失败' % id)
#                else:
#                    wx.CallAfter(self.window.messageCall, '今天%s没有发表新博客' % friend_id)
#        else:
#            wx.CallAfter(self.window.messageCall, '获取好友列表失败')



            
        
if __name__ == '__main__':
    import doctest
    doctest.testmod()         
